<template>
  <div>
    <Poptip confirm transfer ref="pop"
            v-if="pop"
            :title="title"
            :style="{width:'100%',margin:'5px 0'}"
            @on-ok="click">
      <Button v-bind="$attrs" :loading="loading" style="width:100%;"><slot><span :style="textStyle">{{text}}</span></slot></Button>
    </Poptip>
    <Button v-else :style="{width:'100%'}" v-bind="$attrs" :loading="loading" @click="click"><slot><span :style="textStyle">{{text}}</span></slot></Button>
  </div>
</template>

<script>
export default {
  name: "starButton",
  data(){
    return {
      loading:false
    }
  },
  props: {
    execution: {
      default: () => {
        return {
          clz: null,
          method: null,
          param: null,
          success: null,
          successMethod:null,
          successParam: null,
          error: null,
          errorMethod:null,
          errorParam: null
        }
      }
    },
    text:{
      default:()=>{
        return ''
      }
    },
    textStyle:{
      default:()=>{
        return {}
      }
    },
    title:{
      default:()=>{
        return ''
      }
    },
    pop:{
      default:()=>{
        return true
      }
    },
    async:{
      default:()=>{
        return true
      }
    },
  },
  mounted() {
    let _this = this;
    if(this.pop&&!!this.$refs.pop){
      let observer = new ResizeObserver(entries => {
        entries[0].target.children[0].style.width='100%'
      })
      this.$nextTick(() => {
        observer.observe(_this.$refs.pop.$el);
      })
    }
  },
  methods:{
    click(e){
      let _this=this;
      if(!!this.execution.clz&&!!this.execution.method){
        this.loading=true;
        if(!!this.async){
          this.execution.clz[this.execution.method](this.execution.param).then(flag=>{
            this.handleResult(flag);
          })
        }else{
          let flag=this.execution.clz[this.execution.method](this.execution.param);
          this.handleResult(flag);
        }
      }
    },
    handleResult(flag){
      if(!!flag){
        if(!!this.execution.success&&!!this.execution.successMethod){
          this.execution.success[this.execution.successMethod](this.execution.successParam);
        }
      }else{
        if(!!this.execution.error&&!!this.execution.errorMethod){
          this.execution.error[this.execution.errorMethod](this.execution.errorParam);
        }
      }
      this.loading=false;
      this.$emit('complete',flag)
    }
  }
}
</script>

<style scoped>

</style>